package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-11-02 10:10
 **/
public class LeetCode79 {

    public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (dfs(board, words, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, char[] words, int i, int j, int k) {
        //如果i,j越界或者board[i][j]不等于words[k],直接返回false
        if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != words[k]) {
            return false;
        }
        if (k == words.length - 1) {
            return true;
        }
        //给board[i][j]置为空字符使得该位置不能被重复遍历
        board[i][j] = '\0';
        //如果上下左右有一个方向遍历成功即为成功。
        boolean res = dfs(board, words, i - 1, j, k + 1) || dfs(board, words, i, j - 1, k + 1) ||
                dfs(board, words, i + 1, j, k + 1) || dfs(board, words, i, j + 1, k + 1);
        //再把board[i][j]变回去，因为如果res为false，下一轮就重新开始，可能还会遍历到当前节点。
        board[i][j] = words[k];
        return res;
    }

}
